package com.example.ivideo_2211a.search

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.common.mvi.BaseActivity
import com.example.ivideo_2211a.R
import com.example.ivideo_2211a.databinding.ActivitySearchBinding
import com.google.gson.Gson

@Route(path = "/app/SearchActivity")
class SearchActivity :
    BaseActivity<ActivitySearchBinding, SearchViewModel, SearchIntent, SearchViewState>() {
    override val viewModel: SearchViewModel by viewModels()

    override fun getLayoutId() = R.layout.activity_search
    private lateinit var hotAdapter: SearchHotAdapter

    override fun setupViews() {
        currentHotAdapter()
        binding.ivBack.setOnClickListener {
            finish()
        }
        hotAdapter.setOnItemClickListener(object : SearchHotAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, data: String) {
                ToastUtils.showShort(data)
            }
        })
        binding.btnSearch.setOnClickListener {
            if (binding.etSearch.text.toString().isEmpty()) return@setOnClickListener
            addSearchHistory(binding.etSearch.text.toString())
        }
    }

    private fun addSearchHistory(toString: String) {

        sendIntent(SearchIntent.Search(toString, 1, 10))
    }

    private fun currentHotAdapter() {
        //此处可以根据后端返回的数据进行适配
        val list = arrayListOf("热门1", "热门2", "热门3", "热门4", "热门5")
        hotAdapter = SearchHotAdapter(list)
        binding.rcHotSearch.layoutManager = GridLayoutManager(this, 2)
        binding.rcHotSearch.adapter = hotAdapter
    }

    override fun renderViewState(state: SearchViewState) {
        if (state.isLoading == true){
            ARouter.getInstance().build("/app/SearchDetailtActivity")
                .withString("videoInfo", Gson().toJson(state.videos))
                .navigation()
        }

    }
}